<?php namespace Home\Controller;
use Hdphp\Controller\Controller;

class GoodsController extends Controller{
	private $model;
	public function __init(){

		$this->model = new \Admin\Model\Goods;
	}
	public function index(){
		$goodsdata=$this->model
			->where("gid=".Q('get.gid',0,'intval'))
			->join('goodsdes','gid','=','goods_gid')
			->join('category','category_cid','=','cid')
			->join('brand','brand_bid','=','bid')
			->get();
		View::with('goodsdata',$goodsdata);
		
		$goodsattr=Db::table('goodsattr')->join('typeattr','typeattr_taid','=','taid')->where("goods_gid=".Q('get.gid',0,'intval'))->get();
//		获得最大的附加价格 用于商品价格的取值范围
		$maxadd = 0;
		foreach ($goodsattr as $k => $v) {
			if($v['taclass']==1){
				foreach (explode(',',$v['gaadd']) as $kk => $vv){
					if($vv>$maxadd) {$maxadd = $vv;}
				}
			}
			
		}
		View::with('maxadd',$maxadd);
		View::with('goodsattr',$goodsattr);
	    View::make();
	}
	
//	Ajax
	public function cho(){
		$g = Q('post.g',0,'intval');
		$a = Q('post.a','');
		$c = Q('post.c','');
		$data = array();
		$gldata = Db::table('goodslist')->where("goods_gid={$g}")->get();
//		计算价格
		$add = 0;
		foreach (explode(',',$a) as $value) {
			$add = $add+$value;
		}
//		加在data里
		$data['add'] = "{$add}";

//		循环数据库
		$temp = 0;
		foreach ($gldata as $k => $v) {
			if($v['glattrid'].','==$c){
				$data['glinv'] = $v['glinv'];
				$temp = 1;
			}
//			如果都不等于
			if($temp==0){
				$data['glinv'] = 0;
			}
		}
		echo json_encode($data);exit;
		
	}

	//放到购物车
	public function incart(){
		$g = Q('post.g',0,'intval');
		$a = Q('post.a','');
		$c = Q('post.c','');
		$nu = Q('post.nu',0,'intval');
		$ta = explode(',',Q('post.ta',''));
		//库存
		$li = Q('post.li',0,'intval');
		//判断是否大于库存
		if($nu>$li) {echo json_encode(array('re'=>'3'));exit;}
		//		计算价格
		$add = 0;
		foreach (explode(',',$a) as $value) {
			$add = $add+$value;
		}
		//查询数据库
		$goodsdata1 = $this->model->where("gid=".$g)->get();
		//判断查询的数据是否有 防止更改前台数据
		if($goodsdata1){
			$data = array(
			'id' => $g,
			'name' => $goodsdata1[0]['gname'],
			'num' => $nu,
			'price' => $add+$goodsdata1[0]['gshopprice'],
			//添加库存 用在购物车里选择购物数量的最大值
			'mydata'=>$li,
			);
			//循环规格名称
			foreach ($ta as $k => $v) {
				foreach (explode(',',rtrim($c, ",")) as $kk =>  $vv) {
					if($k==$kk){
						$data['options'][$v] = $vv;
					}
				}
			}
			Cart::add($data);
			echo json_encode(array('re'=>'1','num'=>Cart::getTotalNums(),'pri'=>Cart::getTotalPrice()));exit;
		}else{
			echo json_encode(array('re'=>'0'));exit;
		}
		
		
		
	}
	
	
	
	
	
	
	
}
	